package io.renren.modules.generator.service.impl;

import io.renren.common.utils.ShiroUtils;
import io.renren.modules.generator.dto.DynamicDto;
import io.renren.modules.generator.entity.PhotoEntity;
import io.renren.modules.generator.entity.UserLikeEntity;
import io.renren.modules.generator.service.PhotoService;
import io.renren.modules.generator.service.UserLikeService;
import io.renren.modules.generator.vo.DynamicVo;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.generator.dao.DynamicDao;
import io.renren.modules.generator.entity.DynamicEntity;
import io.renren.modules.generator.service.DynamicService;
import org.springframework.transaction.annotation.Transactional;


@Service("dynamicService")
@Transactional
public class DynamicServiceImpl extends ServiceImpl<DynamicDao, DynamicEntity> implements DynamicService {

    @Autowired
    private PhotoService photoService;

    @Autowired
    private UserLikeService userLikeService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<DynamicEntity> page = this.page(
                new Query<DynamicEntity>().getPage(params),
                new QueryWrapper<DynamicEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveDynamic(DynamicDto dynamic) {
        DynamicEntity dynamicEntity = new DynamicEntity();
        SysUserEntity userEntity = ShiroUtils.getUserEntity();
        dynamicEntity.setCreateTime(new Date());
        dynamicEntity.setUserId(userEntity.getUserId());
        dynamicEntity.setUsername(userEntity.getUsername());
        dynamicEntity.setDynamicContent(dynamic.getDynamicContent());
        //处理评论
        Integer id = dynamic.getDynamicId();
        if (Objects.nonNull(id)) {
            dynamicEntity.setParentId(id);
            //原先的说说
            DynamicEntity oldDynamic = baseMapper.selectById(id);
            DynamicEntity newDynamic = new DynamicEntity();
            newDynamic.setDynamicId(id);
            //原有评论数加一
            newDynamic.setCommentNum(oldDynamic.getCommentNum() + 1);
            baseMapper.updateById(newDynamic);
        }
        baseMapper.insert(dynamicEntity);
        String[] photoUrls = dynamic.getPhotoUrls();
        if (Objects.nonNull(photoUrls) && photoUrls.length > 0) {
            Integer dynamicId = dynamicEntity.getDynamicId();
            for (String photoUrl : photoUrls) {
                PhotoEntity photoEntity = new PhotoEntity();
                photoEntity.setDynamicId(dynamicId);
                photoEntity.setPhotoUrl(photoUrl);
                photoService.save(photoEntity);
            }
        }
    }

    @Override
    public List<DynamicVo> getMyDynamic() {
        Long userId = ShiroUtils.getUserId();
        List<DynamicVo> dynamics = baseMapper.getDynamics(userId);
        dynamics.forEach(dynamicVo -> {
            List<PhotoEntity> photos = dynamicVo.getPhotos();
            List<String> photoUrls = new ArrayList<>();
            photos.forEach(photoEntity -> {
                photoUrls.add(photoEntity.getPhotoUrl());
            });
            dynamicVo.setPhotoUrls(photoUrls);
        });
        //获取评论的子评论信息
        return setChildrens(dynamics);
    }

    @Override
    public List<DynamicVo> getAllInfo() {
        List<DynamicVo> dynamics = baseMapper.getDynamics(null);
        dynamics.forEach(dynamicVo -> {
            List<PhotoEntity> photos = dynamicVo.getPhotos();
            List<String> photoUrls = new ArrayList<>();
            photos.forEach(photoEntity -> {
                photoUrls.add(photoEntity.getPhotoUrl());
            });
            dynamicVo.setPhotoUrls(photoUrls);
        });
        //获取评论的子评论信息
        List<DynamicVo> dynamicVos = setChildrens(dynamics);
        //获取该用户是否点赞信息
        return getUserLikeInfo(dynamicVos);
    }

    @Override
    public void removeDynamic(Integer dynamicId) {
        QueryWrapper<PhotoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("dynamic_id", dynamicId);
        List<PhotoEntity> list = photoService.list(wrapper);
        if (!list.isEmpty()) {
            List<Integer> ids = new ArrayList<>();
            for (PhotoEntity photoEntity : list) {
                ids.add(photoEntity.getPhotoId());
            }
            photoService.removeByIds(ids);
        }
        //删除子评论
        QueryWrapper<DynamicEntity> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("parent_id", dynamicId);
        baseMapper.delete(wrapper1);

        //删除点赞关系
        QueryWrapper<UserLikeEntity> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("dynamic_id", dynamicId);
        userLikeService.remove(wrapper2);

        baseMapper.deleteById(dynamicId);

    }

    @Override
    public void cancelLike(Integer dynamicId) {
        Long userId = ShiroUtils.getUserId();
        DynamicEntity dynamicEntity = baseMapper.selectById(dynamicId);
        DynamicEntity dynamic = new DynamicEntity();
        dynamic.setDynamicId(dynamicEntity.getDynamicId());
        //点赞量减一
        dynamic.setLikeNum(dynamicEntity.getLikeNum() - 1);
        //删除用户和点赞之间的关系
        QueryWrapper<UserLikeEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("dynamic_id", dynamicId);
        userLikeService.remove(wrapper);
        baseMapper.updateById(dynamic);
    }

    @Override
    public void like(Integer dynamicId) {
        Long userId = ShiroUtils.getUserId();
        DynamicEntity dynamicEntity = baseMapper.selectById(dynamicId);
        DynamicEntity dynamic = new DynamicEntity();
        dynamic.setDynamicId(dynamicEntity.getDynamicId());
        //点赞量加一
        dynamic.setLikeNum(dynamicEntity.getLikeNum() + 1);
        //保存用户和点赞之间的关系
        UserLikeEntity userLikeEntity = new UserLikeEntity();
        userLikeEntity.setUserId(userId);
        userLikeEntity.setDynamicId(dynamicId);
        userLikeService.save(userLikeEntity);
        baseMapper.updateById(dynamic);
    }

    private List<DynamicVo> setChildrens(List<DynamicVo> dynamicVos) {
        if (!CollectionUtils.isEmpty(dynamicVos)) {
            dynamicVos.forEach(dynamicVo -> {
                Integer dynamicId = dynamicVo.getDynamicId();
                List<DynamicVo> childrenDynamic = baseMapper.getChildrenDynamic(dynamicId);
                dynamicVo.setChildrens(childrenDynamic);
                setChildrens(childrenDynamic);
            });
        }
        return dynamicVos;
    }

    /**
     * 获取用户点赞信息
     *
     * @param dynamicVos
     * @return
     */
    private List<DynamicVo> getUserLikeInfo(List<DynamicVo> dynamicVos) {
        Long userId = ShiroUtils.getUserId();
        dynamicVos.forEach(dynamicVo -> {
            Integer dynamicId = dynamicVo.getDynamicId();
            QueryWrapper<UserLikeEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId).eq("dynamic_id", dynamicId);
            UserLikeEntity userLikeEntity = userLikeService.getOne(wrapper);
            if (Objects.nonNull(userLikeEntity)) {
                dynamicVo.setLike(true);
            } else {
                dynamicVo.setLike(false);
            }
        });
        return dynamicVos;
    }

}
